package com.woniuxy.mesboot.security;

import cn.hutool.core.util.StrUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.woniuxy.mesboot.util.JwtUtils;
import com.woniuxy.mesboot.util.Result;
import com.woniuxy.mesboot.util.ServiceCode;
import io.jsonwebtoken.Claims;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author ：lisir
 * @date ：Created in 2023/5/30 11:03
 * @description：TODO
 */
@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Autowired
    private JwtUtils jwtUtils;
    @Autowired
    private UserDetailsService userDetailsService;
    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
//        1.拿到token
        String token = request.getHeader("Authorization");
        //2判断是否为空,如果为空直接放行
        if (StrUtil.isEmptyOrUndefined(token)) {
            filterChain.doFilter(request,response);
            return;
        }
        //3.判断token是否为该服务器发出的token
        Claims claims = jwtUtils.getClaimsByToken(token);
        if (claims == null) {
            String s = new ObjectMapper().writeValueAsString(Result.error(ServiceCode.ERR_JWT_PARSE,"非法token"));
            response.getWriter().println(s);
            return;
        }
        //4.判断是否过期
        if (jwtUtils.isTokenExpired(claims)) {
            String s = new ObjectMapper().writeValueAsString(Result.error(ServiceCode.ERR_JWT_EXPIRED,"token已过期"));
            response.getWriter().println(s);
            return;
        }
        //能走到这里说明是合法的token
        String username = claims.getSubject();
        LoginUser loginUser = (LoginUser) userDetailsService.loadUserByUsername(username);
        UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(loginUser, null, loginUser.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(request,response);
    }
}
